#coding=utf-8
from stseries import *
from stindex.indexdb import get_exdayslist
from stutils import set_django_environ
set_django_environ()
from stdj.stock.models import *

eds = get_exdayslist(start='2007-01-01')
def init_myindex():
    
    for t in Tag.objects.all():
        ss = t.share_set.all()
        print t, ss.count()
        if ss.count() == 0 :continue
        
        pre = 1
        for ed in eds:
            ps = []
            for s in ss:
                try:
                    ps.append( s.exday_set.get(date=ed).price)
                except Exday.DoesNotExist, e:
                    continue
                    
            if not ps:continue    
            change = average( [p.change for p in ps if p.change] )
            hsl = average( [p.hsl for p in ps if p.hsl] )
            price = pre * (1 + change/100) 
            
            m = MyIndex()
            m.name = t.name
            m.date = ed
            m.price = price 
            m.change = change
            m.hsl = hsl
            
            m.save()
            
            pre = price
            print ed, price

import datetime
td = datetime.date.today().isoformat()
def update(ed=td):
    for t in Tag.objects.all():
        m = MyIndex.objects.filter(name=t).filter(date__lt=ed).order_by('-date')[0]
        pre = m.price
         
        ps = []
        for s in ss:
            try:
                ps.append( s.exday_set.get(date=ed).price)
            except Exday.DoesNotExist, e:
                continue
                    
            if not ps:continue    
            change = average( [p.change for p in ps if p.change] )
            hsl = average( [p.hsl for p in ps if p.hsl] )
            price = pre * (1 + change/100) 
            
            m = MyIndex()
            m.name = t.name
            m.date = ed
            m.price = price 
            m.change = change
            m.hsl = hsl
            
            m.save()
            
if __name__ == '__main__':
    init_myindex()